<template>
	<div>
		<el-cascader 
			clearable 
			size="mini" 
			:options="cities"
			 @change="getCities"
			  @active-item-change="handleItemChange">
		</el-cascader>
	</div>
</template>

<script>
	export default {
		created() {
			this.getFirstClassify();
		},
		data() {
			return {
				cities: [],
				_cities: [],
				deep: 1,
			}
		},
		props: ["is_open"],
		methods: {
			//获取一级分类
			getFirstClassify() {
				var url = `${this.url}/area/area_get_first_list.action`;
				var params = {};
				if(this.is_open != undefined && this.is_open != null) {
					if(this.is_open == 1) {
						params = {
							is_open: this.is_open
						}
					} else {
						url = this.url + '/area/area_get_first_list_no_open.action';
					}
				}
				this.$http.get(url, {
					params
				}).then((res) => {
					if(res.data.success) {
						res.data.result.rows.forEach(val => {
							this.cities.push({
								value: val.area_id,
								label: val.area_name,
								children: []
							});
						});
					} else {
						this.$message({
							type: "error",
							message: res.data.result.errmsg
						});
					}
				});

			},
			//获取子分类
			handleItemChange(val) {
				var url = `${this.url}/area/area_get_sub_list.action`;
				var params = {
					area_id: val[val.length - 1]
				}
				if(this.is_open != undefined && this.is_open != null) {
					if(this.is_open == 1 || val.length == 2) {
						params["is_open"] = this.is_open;
					} else {
						url = this.url + '/area/area_get_second_list_no_open.action';
					}
				}
				this.deep = val.length;
				this.$http.get(url, {
					params
				}).then((res) => {
					if(this.deep === 1) {
						this.cities.forEach(value => {
							if(value.value === val[val.length - 1]) {
								res.data.result.rows.forEach(item => {
									value.children.push({
										value: item.area_id,
										label: item.area_name,
										children: []
									});
								});
								this._cities = value.children;
							}
						});
					} else if(this.deep === 2) {
						this._cities.forEach(value => {
							if(value.value === val[val.length - 1]) {
								res.data.result.rows.forEach(item => {
									value.children.push({
										value: item.area_id,
										label: item.area_name
									});
								});
							}
						});
					}
				});
			},
			//获取全部城市列表
			getCities(val) {
				this.$emit("getArea", val[val.length - 1]);
			},

		}
	}
</script>

<style lang="scss" scoped>

</style>